package com.ag.admin.service.impl;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import com.ag.admin.dao.TbRoleDAO;
import com.ag.admin.security.support.SecurityManagerSupport;
import com.ag.admin.utils.UserUtil;
import com.ag.bean.TbPermission;
import com.ag.bean.TbRole;
import com.ag.bean.TbRolePermission;
import com.ag.bean.TbRolePermissionId;
import com.ag.common.AgException;
import com.ag.common.IBaseService;
import com.ag.common.IDUtil;
import com.ag.dao.TbPermissionDAO;
import com.ag.dao.TbRolePermissionDAO;

@Service("roleServiceImpl")
public class RoleServiceImpl implements IBaseService<TbRole, String> {

	private static final Logger logger = Logger
			.getLogger(RoleServiceImpl.class);

	@Resource(name = "adminTbRoleDAO")
	private TbRoleDAO roleDAO;
	@Resource(name = "TbPermissionDAO")
	private TbPermissionDAO PermissionDAO;
	@Resource(name = "TbRolePermissionDAO")
	private TbRolePermissionDAO rpdao;

	/**
	 * 根据角色ID保存角色权限
	 * 
	 * @throws Exception
	 */
	/**
	 * 调用权限服务逻辑组件
	 */
	@Resource(name = "securityManager")
	private SecurityManagerSupport sms;

	public void saveRolePmsnByRoleId(String RId, String rolePmsnStr,
			ServletContext servletContext) throws Exception {
		String hsql = "delete from TbRolePermission rp where rp.id.RId = '"
				+ RId + "'";
		roleDAO.execute(hsql);
		if (rolePmsnStr != null && !rolePmsnStr.isEmpty()) {
			String[] rpArr = rolePmsnStr.split(",");
			for (String st : rpArr) {
				TbRolePermission tbrp = new TbRolePermission();
				TbRolePermissionId rpid = new TbRolePermissionId();
				rpid.setRId(RId);
				rpid.setPId(st);
				tbrp.setId(rpid);
				rpdao.save(tbrp);
			}
		}
		Map<String, Map<String, TbPermission>> roleAuthorities = sms
				.loadRoleAuthorities();
		servletContext.removeAttribute(UserUtil.ROLE_AUTHORITIES);
		servletContext.setAttribute(UserUtil.ROLE_AUTHORITIES, roleAuthorities);
	}

	/**
	 * 根据角色ID删除角色
	 */
	@Override
	public boolean delete(String id) {
		try {
			TbRole role = roleDAO.findById(id);
			role.setA(IDUtil.DELETE);
			roleDAO.attachDirty(role);
			return true;
		} catch (Exception e) {
			e.printStackTrace();
			throw new AgException("删除角色失败！", e);
		}

		// try {
		// this.roleDAO.delete(this.roleDAO.findById(id));
		// return true;
		// } catch (Exception e) {
		// e.printStackTrace();
		// throw new AgException("删除角色失败！", e);
		// }
	}

	@Override
	public boolean delete(TbRole t) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean update(TbRole t) {
		// TODO Auto-generated method stub
		return false;
	}

	public List<TbRole> findAllRole() {
		// return this.roleDAO.findAll();
		String hsql = "select r from TbRole r where r.a = ?";
		return roleDAO.find(hsql, IDUtil.PRESERVE);
	}

	public List<TbPermission> findAllPermission() {
		// return this.PermissionDAO.findAll();
		String hsql = "select p from TbPermission p order by p.PId asc";
		return roleDAO.find(hsql);
	}

	@Override
	public TbRole findById(String id) {
		// TODO Auto-generated method stub
		return null;
	}

	/**
	 * 保存角色
	 */
	@Override
	public boolean save(TbRole t) {
		String hsql = "select count(*) from TbRole r where r.RName = '"
				+ t.getRName() + "'";
		long cnt = (Long) roleDAO.find(hsql).get(0);
		if (cnt == 0) {
			try {
				roleDAO.save(t);
				return true;
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			String str = "select count(*) from TbRole r where r.RName = '"
					+ t.getRName() + "' and r.a = " + IDUtil.DELETE;
			long cnt1 = (Long) roleDAO.find(hsql).get(0);
			if (cnt1 != 0) {
				TbRole role = roleDAO.findByRName(t.getRName()).get(0);
				role.setA(IDUtil.PRESERVE);
				roleDAO.attachDirty(role);
				return true;
			}
		}
		return false;
	}

	public List<TbPermission> findAllPmsnByRoleId(String RId) {
		String hsql = "select p from TbPermission p join p.tbRolePermissions rp where rp.id.RId = ? order by rp.id.PId asc";
		return roleDAO.find(hsql, RId);
	}
}
